#!/usr/bin/env python3
# -*- coding: utf-8 -*-


'''
MarkdownPage will return a markdown file as string
'''
from wtforms.widgets import HTMLString
import os
from . import markdown


class MarkdownPage(object):
    def __init__(self,strings,parser=None):
        if type(strings) not in (str,):
            strings=strings.read()
        if parser is None:
            parser=markdown()
        self._content=strings
        self._html=None
        self._parser=parser
    def __html__(self):
        return self.html
    def __str__(self):
        return self.html
    @classmethod
    def stysheets(cls):
        import os.path as op
        this_dir=op.dirname(op.abspath(__file__))
        ret={}
        for i in ['markdown/github.css','pygemnts.css']:
            with open(op.join(this_dir,i),'r') as f:
                ret[i]=f.read()
        return ret

    @property
    def markdown(self):
        return self._content
    @property
    def document(self):
        if hasattr(self,'_document') is False:
            from lxml import html
            self._document=html.fromstring(self._parser.convert(self.markdown))
        return self._document
    @property
    def toc(self):
        if hasattr(self,'_toc') is False:
            from lxml import etree
            toc=self.document.find('div[@class="toc"]')
            if toc is None:
                self._toc=HTMLString('')
            else:
                self._toc=HTMLString( etree.tostring(toc).decode('utf8'))
        return self._toc
    @property
    def markdownbody(self):
        if hasattr(self,'_markdownbody') is False:
            from lxml import etree
            mdbody=self.document.find('div[@class="markdown-body"]')
            if mdbody is None:
                self._markdownbody=HTMLString('')
            else:
                self._markdownbody= HTMLString( etree.tostring(mdbody).decode('utf8'))
        return self._markdownbody

    @property
    def html(self):
        if self._html is None:
            self._html=HTMLString(self.toc + self.markdownbody)
        return self._html

class MarkdownFile(MarkdownPage):
    def __init__(self,file_path,siteurl='',parser=None,**kwargs):
        f,ext=os.path.splitext(file_path)
        if ext =='':
            if os.path.exists(file_path +'.md') is True:
                file_path=file_path +'.md'
            elif os.path.exists(file_path +'.markdown') is True:
                file_path=file_path +'.markdown'
        #~ print(f,ext,ext =='',file_path)

        f,ext=os.path.splitext(file_path)
        if os.path.exists(file_path) is False \
            or os.path.isdir(file_path) is True :
            raise Exception('file(%s)  Must be exist and is a regular file' % file_path)
        if ext not in('.md','.markdown'):
            raise Exception("File must endswith ('.md','.markdown') %s" % file_path)
        parser=parser or markdown(os.path.dirname(file_path),**kwargs)
        with open(file_path,'r') as f:
            super(MarkdownFile,self).__init__(f.read(),parser=parser)


class MarkdownDir(MarkdownPage):
    def __init__(self,dir_path,parser=None,suffix=('.md','.markdown'),no_head=False,**kwargs):
        if os.path.exists(dir_path) is False \
            or os.path.isdir(dir_path) is False :
            raise Exception('file  Must be exist and is a directory')

        l=['|file|comment|','|---|---|'] if no_head is False else []
        k=[]
        for entry in os.listdir(dir_path):
            b,e=os.path.splitext(entry)
            if e in suffix:
                k.append((b,e))
            if b.startswith('.'):
                continue
            if os.path.isdir(os.path.join(dir_path,entry)):
                k.append((b + '/',e))

        for b,e in k:
            l.append('|[%s](%s)|test|' %(b,b))
        string='\n'.join(l)
        parser=parser or markdown(os.path.dirname(dir_path),**kwargs)
        super(MarkdownDir,self).__init__(string,parser=parser)
def get_markdown_page(path,parser=None,**kwargs):
    if os.path.isdir(path):
        return MarkdownDir(path,parser=parser,**kwargs)
    return MarkdownFile(path,parser=parser,**kwargs)

def get_page(path):pass







